package com.kim.store.contorller;

import com.kim.store.entity.Address;
import com.kim.store.service.IAddressService;
import com.kim.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController extends BaseController{
    @Autowired
    private IAddressService addressService;


    @RequestMapping("/add_new_address")
    public JsonResult<Void> addNewAddress(HttpSession session, Address address){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.addNewAddress(uid,username,address);
        return new JsonResult<>(OK);
    }

    @RequestMapping({"/",""})
    public JsonResult<List<Address>> getByUid(HttpSession session){
        List<Address> data = addressService.getByUid(getUidFromSession(session));
        return new JsonResult<>(OK,data);
    }

    /**
     * RestFul风格的请求编写
     * localhost8080:/address/set_default/id
     *  @PathVariable("id") Integer aid
     *  这个注解将是前端地址请求参数id 传到控制器方法中的参数列表 aid中
     */
    @RequestMapping("/set_default/{aid}")
    public JsonResult<Void> setDefault(HttpSession session,
                                       @PathVariable("aid") Integer aid){
        addressService.setDefault(aid,
                        getUidFromSession(session),
                        getUsernameFromSession(session));
        return new JsonResult<>(OK);
    }

    @RequestMapping("/delete/{aid}")
    public JsonResult<Void> delete(@PathVariable("aid") Integer aid,
                                   HttpSession session){
        addressService.delete(aid,
                getUidFromSession(session),
                getUsernameFromSession(session));
        return new JsonResult<>(OK);
    }

    @RequestMapping("/update/{aid}")
    public JsonResult<Void> changeAddressInfo(HttpSession session,
                                              @PathVariable("aid") Integer aid,
                                              Address address){
        addressService.changeAddressInfo(aid,getUidFromSession(session),
                getUsernameFromSession(session),address);
        return new JsonResult<>(OK);
    }

    @RequestMapping("/get_by_aid/{aid}")
    public JsonResult<Address> getByAid(@PathVariable Integer aid,HttpSession session){
        Address address = addressService.getByAid(aid,getUidFromSession(session));
        return new JsonResult<>(OK,address);
    }

    @RequestMapping("/href/{aid}")
    public JsonResult<Integer> href(@PathVariable Integer aid){
        return new JsonResult<>(OK);
    }

}
